﻿using System;

namespace Community.CsharpSqlite.Entity
{
    using DbPage = PgHdr;

    public class MemPage
    {
        public byte[] aData; /* Pointer to disk image of the page data */
        public _OvflCell[] aOvfl = new _OvflCell[5];
        public ushort cellOffset; /* Index in aData of first cell pou16er */
        public byte childPtrSize; /* 0 if leaf==1.  4 if leaf==0 */
        public byte hasData; /* True if this page stores data */
        public byte hdrOffset; /* 100 for page 1.  0 otherwise */
        public byte intKey; /* True if bytekey flag is set */
        public byte isInit; /* True if previously initialized. MUST BE FIRST! */
        public byte leaf; /* 1 if leaf flag is set */
        public ushort maskPage; /* Mask for page offset */
        public ushort maxLocal; /* Copy of BtShared.maxLocal or BtShared.maxLeaf */
        public ushort minLocal; /* Copy of BtShared.minLocal or BtShared.minLeaf */
        public ushort nCell; /* Number of cells on this page, local and ovfl */
        public ushort nFree; /* Number of free bytes on the page */
        public byte nOverflow; /* Number of overflow cell bodies in aCell[] */
        public BtShared pBt; /* Pointer to BtShared that this page is part of */
        public DbPage pDbPage; /* Pager page handle */
        public uint pgno; /* Page number for this page */

        public MemPage Copy()
        {
            var cp = (MemPage) MemberwiseClone();
            if (aOvfl != null)
            {
                cp.aOvfl = new _OvflCell[aOvfl.Length];
                for (int i = 0; i < aOvfl.Length; i++) cp.aOvfl[i] = aOvfl[i].Copy();
            }
            if (aData != null)
            {
                cp.aData = Malloc.sqlite3Malloc(aData.Length);
                Buffer.BlockCopy(aData, 0, cp.aData, 0, aData.Length);
            }
            return cp;
        }
    };
}